#include "TestPulleyJoint.h"
#include "Tools.h"

CCScene* TestPulleyJoint::scene()
{
	CCScene* sc = CCScene::create();
	TestPulleyJoint* layer = TestPulleyJoint::create();
	sc->addChild(layer);

	return sc;
}

bool TestPulleyJoint::init()
{
	BaseLayer::init();

	initJoint();
	
	scheduleUpdate();

	return true;
}

void TestPulleyJoint::initJoint()
{
	const b2Vec2 groundVec1(Tools::convertTob2WorldSpace(ccp(winSize.width/4, winSize.height*8/9)));
	const b2Vec2 groundVec2(Tools::convertTob2WorldSpace(ccp(winSize.width*3/4, winSize.height*8/9)));

	b2Body *ground = NULL;
	{
		b2BodyDef bd;
		ground = m_world->CreateBody(&bd);

		b2CircleShape circle;
		circle.m_radius = 1.0f;

		circle.m_p.Set(groundVec1.x, groundVec1.y);
		ground->CreateFixture(&circle, 0.0f);

		circle.m_p.Set(groundVec2.x, groundVec2.y);
		ground->CreateFixture(&circle, 0.0f);
	}

	b2Body* bodyA = NULL;
	b2Body* bodyB = NULL;
	{
		b2PolygonShape shape;
		shape.SetAsBox(1.0f, 2.0f);

		b2BodyDef bodyDef;
		bodyDef.type = b2_dynamicBody;
		
		bodyDef.position.Set(groundVec1.x, groundVec1.y - 10);
		bodyA = m_world->CreateBody(&bodyDef);

		b2FixtureDef fixDef;
		fixDef.density = 1.0f;
		fixDef.friction = 0.3f;
		fixDef.restitution = 3.0f;
		fixDef.shape = &shape;

		bodyA->CreateFixture(&fixDef);

		bodyDef.position.Set(groundVec2.x, groundVec2.y - 12);
		bodyB = m_world->CreateBody(&bodyDef);

		fixDef.restitution = 2.0f;
		bodyB->CreateFixture(&fixDef);
	}

	b2PulleyJointDef pulleyDef;
	b2Vec2 anchor1 = bodyA->GetWorldCenter();
	b2Vec2 anchor2 = bodyB->GetWorldCenter();
	b2Vec2 groundAnchor1(groundVec1.x, groundVec1.y);
	b2Vec2 groundAnchor2(groundVec2.x, groundVec2.y);
	pulleyDef.Initialize(bodyA, bodyB, groundAnchor1, groundAnchor2, anchor1, anchor2, 1.5f);
	m_world->CreateJoint(&pulleyDef);
}

void TestPulleyJoint::update(float dt)
{
	m_world->Step(dt, 8, 1);
}